import React, { useState, useEffect, useCallback } from 'react';
import {
  Container,
  Grid,
  Card,
  CardContent,
  CardActions,
  Typography,
  Button,
  TextField,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Alert,
  Box,
} from '@mui/material';
import { format } from 'date-fns';
import { apiRequest, API_PATHS } from '../config/api';

interface Movie {
  _id: string;
  title: string;
  description: string;
  remainingTickets: number;
  price: number;
  showtime: string;
}

const MovieList: React.FC = () => {
  const [movies, setMovies] = useState<Movie[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedMovie, setSelectedMovie] = useState<Movie | null>(null);
  const [ticketQuantity, setTicketQuantity] = useState(1);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [openDialog, setOpenDialog] = useState(false);

  const fetchMovies = useCallback(async () => {
    try {
      setLoading(true);
      setError('');
      const data = await apiRequest<Movie[]>(API_PATHS.MOVIES);

      
      // 根据放映时间降序排序
      const sortedMovies = data.sort((a: Movie, b: Movie) => new Date(b.showtime).getTime() - new Date(a.showtime).getTime());
      setMovies(sortedMovies);
    } catch (error) {
      setError(error instanceof Error ? error.message : '获取电影列表失败');
      setMovies([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    fetchMovies();
  }, [fetchMovies]);

  const handlePurchase = async () => {
    if (!selectedMovie) {
      setError('未选择电影');
      return;
    }

    if (ticketQuantity <= 0 || ticketQuantity > selectedMovie.remainingTickets) {
      setError('购票数量无效');
      return;
    }

    try {
      setError('');
      setSuccess('');
      
      const token = localStorage.getItem('token');
      if (!token) {
        setError('请先登录');
        return;
      }

      const data = await apiRequest(API_PATHS.ORDERS, {
        method: 'POST',
        body: JSON.stringify({
          movieId: selectedMovie._id,
          quantity: ticketQuantity,
        }),
      });

      setSuccess('购票成功！');
      setOpenDialog(false);
      setTicketQuantity(1);
      await fetchMovies(); // 刷新电影列表
    } catch (error) {
      setError(error instanceof Error ? error.message : '服务器连接失败');
    }
  };

  const handleOpenDialog = (movie: Movie) => {
    setSelectedMovie(movie);
    setOpenDialog(true);
    setError('');
    setSuccess('');
  };

  const handleCloseDialog = () => {
    setOpenDialog(false);
    setSelectedMovie(null);
    setTicketQuantity(1);
    setError('');
  };

  return (
    <Container sx={{
      minHeight: '100vh',
      position: 'relative',
      '&::before': {
        content: "''",
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        background: 'linear-gradient(135deg, #0a192f 0%, #203a43 100%)',
        zIndex: -2,
      },
      '&::after': {
        content: "''",
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.03'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
        backgroundRepeat: 'repeat',
        opacity: 0.3,
        zIndex: -1,
      }
    }}>
      <Typography variant="h4" component="h1" gutterBottom sx={{
        mt: 4,
        mb: 4,
        color: '#ffffff',
        textAlign: 'center',
        fontWeight: 'bold',
        textShadow: '2px 2px 4px rgba(0,0,0,0.5)',
        position: 'relative'
      }}>
        正在热映
      </Typography>

      <Grid container spacing={2}>
        {movies.map((movie) => (
          <Grid item xs={12} sm={6} md={2.4} key={movie._id}>
            <Card sx={{
              height: '100%',
              minHeight: '320px',
              display: 'flex',
              flexDirection: 'column',
              background: 'linear-gradient(135deg, #1a237e 0%, #0d47a1 100%)',
              color: 'white',
              transition: 'transform 0.3s ease-in-out, box-shadow 0.3s ease-in-out',
              '&:hover': {
                transform: 'translateY(-8px)',
                boxShadow: '0 12px 20px rgba(0,0,0,0.3)'
              },
              position: 'relative',
              overflow: 'hidden',
              borderRadius: '12px'
            }}>
              <CardContent sx={{
                flexGrow: 1,
                minHeight: '240px',
                display: 'flex',
                flexDirection: 'column',
                justifyContent: 'space-between',
                position: 'relative',
                zIndex: 1,
                '&::before': {
                  content: '""',
                  position: 'absolute',
                  top: 0,
                  left: 0,
                  right: 0,
                  bottom: 0,
                  background: 'linear-gradient(180deg, rgba(0,0,0,0) 0%, rgba(0,0,0,0.8) 100%)',
                  zIndex: -1
                }
              }}>
                <Box>
                  <Typography variant="h6" component="h2" gutterBottom
                    sx={{
                      fontWeight: 'bold',
                      textShadow: '2px 2px 4px rgba(0,0,0,0.5)',
                      fontSize: '1.2rem',
                      mb: 2,
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      display: '-webkit-box',
                      WebkitLineClamp: 2,
                      WebkitBoxOrient: 'vertical',
                      minHeight: '3.6em'
                    }}>
                    {movie.title}
                  </Typography>
                  <Typography variant="body2" sx={{
                    color: 'rgba(255,255,255,0.8)',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    display: '-webkit-box',
                    WebkitLineClamp: 3,
                    WebkitBoxOrient: 'vertical',
                    mb: 2,
                    minHeight: '4.5em',
                    fontSize: '0.875rem',
                    lineHeight: 1.5
                  }}>
                    {movie.description}
                  </Typography>
                </Box>
                <Box sx={{ mt: 'auto' }}>
                  <Typography variant="body2" sx={{ color: 'rgba(255,255,255,0.9)', mb: 0.5 }}>
                    放映时间: {format(new Date(movie.showtime), 'yyyy-MM-dd HH:mm')}
                  </Typography>
                  <Typography variant="h6" sx={{ color: '#ffd700', fontWeight: 'bold', mb: 0.5 }}>
                    ¥{movie.price}
                  </Typography>
                  <Typography variant="body2" sx={{
                    color: movie.remainingTickets > 0 ? '#4caf50' : '#f44336',
                    fontWeight: 'bold'
                  }}>
                    {movie.remainingTickets > 0 ? `剩余票数: ${movie.remainingTickets}` : '已售罄'}
                  </Typography>
                </Box>
              </CardContent>
              <CardActions sx={{ p: 2, pt: 0 }}>
                <Button
                  size="large"
                  variant="contained"
                  onClick={() => handleOpenDialog(movie)}
                  disabled={movie.remainingTickets === 0}
                  fullWidth
                  sx={{
                    background: 'linear-gradient(45deg, #ff6b6b 30%, #ff8e53 90%)',
                    color: 'white',
                    fontWeight: 'bold',
                    '&:hover': {
                      background: 'linear-gradient(45deg, #ff8e53 30%, #ff6b6b 90%)'
                    },
                    '&.Mui-disabled': {
                      background: 'rgba(0,0,0,0.3)',
                      color: 'rgba(255,255,255,0.4)'
                    }
                  }}
                >
                  {movie.remainingTickets > 0 ? '购票' : '已售罄'}
                </Button>
              </CardActions>
            </Card>
          </Grid>
        ))}
      </Grid>

      {loading && (
        <Typography align="center" sx={{ my: 2 }}>
          加载中...
        </Typography>
      )}

      <Dialog
        open={openDialog}
        onClose={handleCloseDialog}
        maxWidth="sm"
        fullWidth
        PaperProps={{
          sx: {
            borderRadius: '16px',
            background: 'linear-gradient(135deg, #2c3e50 0%, #3498db 100%)',
            color: 'white',
            overflow: 'hidden',
            position: 'relative',
            '&::before': {
              content: '""',
              position: 'absolute',
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
              background: 'url("https://www.transparenttextures.com/patterns/movie.png")',
              opacity: 0.1,
              zIndex: 0,
            }
          }
        }}
      >
        <DialogTitle sx={{
          textAlign: 'center',
          fontSize: '1.5rem',
          fontWeight: 'bold',
          background: 'rgba(0,0,0,0.3)',
          borderBottom: '1px solid rgba(255,255,255,0.1)',
          position: 'relative',
          zIndex: 1
        }}>
          购买电影票
        </DialogTitle>
        <DialogContent sx={{ position: 'relative', zIndex: 1 }}>
          {error && <Alert severity="error" sx={{ mb: 2, mt: 2 }}>{error}</Alert>}
          {success && <Alert severity="success" sx={{ mb: 2, mt: 2 }}>{success}</Alert>}
          {selectedMovie && (
            <Box sx={{
              mt: 2,
              display: 'flex',
              flexDirection: 'column',
              gap: 2,
              position: 'relative'
            }}>
              <Typography variant="h5" sx={{
                fontWeight: 'bold',
                textShadow: '2px 2px 4px rgba(0,0,0,0.3)',
                mb: 1
              }}>
                {selectedMovie.title}
              </Typography>
              <Box sx={{
                display: 'flex',
                alignItems: 'center',
                gap: 2,
                p: 2,
                borderRadius: '8px',
                background: 'rgba(255,255,255,0.1)',
                backdropFilter: 'blur(10px)'
              }}>
                <Box sx={{ flex: 1 }}>
                  <Typography variant="body2" sx={{ color: 'rgba(255,255,255,0.7)', mb: 1 }}>
                    单价
                  </Typography>
                  <Typography variant="h6" sx={{
                    color: '#ffd700',
                    fontWeight: 'bold',
                    display: 'flex',
                    alignItems: 'baseline',
                    gap: 0.5
                  }}>
                    <span style={{ fontSize: '0.8rem' }}>¥</span>
                    {selectedMovie.price.toFixed(2)}
                  </Typography>
                </Box>
                <Box sx={{
                  flex: 1,
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'flex-end'
                }}>
                  <Typography variant="body2" sx={{ color: 'rgba(255,255,255,0.7)', mb: 1 }}>
                    剩余票数
                  </Typography>
                  <Typography variant="h6" sx={{ fontWeight: 'bold', color: '#4caf50' }}>
                    {selectedMovie.remainingTickets}
                  </Typography>
                </Box>
              </Box>
              <Box sx={{
                mt: 2,
                p: 2,
                borderRadius: '8px',
                background: 'rgba(255,255,255,0.1)',
                backdropFilter: 'blur(10px)'
              }}>
                <Typography variant="body2" sx={{ color: 'rgba(255,255,255,0.7)', mb: 1 }}>
                  购票数量
                </Typography>
                <Box sx={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 2
                }}>
                  <Button
                    variant="contained"
                    size="small"
                    onClick={() => setTicketQuantity(Math.max(1, ticketQuantity - 1))}
                    sx={{
                      minWidth: '40px',
                      background: 'rgba(255,255,255,0.2)',
                      '&:hover': { background: 'rgba(255,255,255,0.3)' }
                    }}
                  >
                    -
                  </Button>
                  <Typography sx={{ flex: 1, textAlign: 'center', fontWeight: 'bold' }}>
                    {ticketQuantity}
                  </Typography>
                  <Button
                    variant="contained"
                    size="small"
                    onClick={() => setTicketQuantity(Math.min(selectedMovie.remainingTickets, ticketQuantity + 1))}
                    sx={{
                      minWidth: '40px',
                      background: 'rgba(255,255,255,0.2)',
                      '&:hover': { background: 'rgba(255,255,255,0.3)' }
                    }}
                  >
                    +
                  </Button>
                </Box>
              </Box>
              <Box sx={{
                mt: 2,
                p: 2,
                borderRadius: '8px',
                background: 'rgba(255,255,255,0.1)',
                backdropFilter: 'blur(10px)',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center'
              }}>
                <Typography variant="body1" sx={{ color: 'rgba(255,255,255,0.9)' }}>
                  总价
                </Typography>
                <Typography variant="h5" sx={{
                  color: '#ffd700',
                  fontWeight: 'bold',
                  display: 'flex',
                  alignItems: 'baseline',
                  gap: 0.5
                }}>
                  <span style={{ fontSize: '1rem' }}>¥</span>
                  {(selectedMovie.price * ticketQuantity).toFixed(2)}
                </Typography>
              </Box>
            </Box>
          )}
        </DialogContent>
        <DialogActions sx={{
          borderTop: '1px solid rgba(255,255,255,0.1)',
          background: 'rgba(0,0,0,0.3)',
          position: 'relative',
          zIndex: 1,
          p: 2
        }}>
          <Button
            onClick={handleCloseDialog}
            sx={{
              color: 'rgba(255,255,255,0.7)',
              '&:hover': { color: 'white' }
            }}
          >
            取消
          </Button>
          <Button
            onClick={handlePurchase}
            variant="contained"
            sx={{
              background: 'linear-gradient(45deg, #ff6b6b 30%, #ff8e53 90%)',
              fontWeight: 'bold',
              '&:hover': {
                background: 'linear-gradient(45deg, #ff8e53 30%, #ff6b6b 90%)'
              }
            }}
          >
            确认购买
          </Button>
        </DialogActions>
      </Dialog>
    </Container>
  );
};

export default MovieList;